package Concurrency.basic.cooperation;

/**
 * 使用wait/notify进行协作
 * 注意：wait/notify必须要在synchronized修饰的代码块中使用，否则会报IllegalMonitorStateException
 */

public class WaitThread extends Thread{
    private volatile boolean fire = false;

    @Override
    public void run() {
       try {
           synchronized (this) {
               while (!fire) {
                   System.out.println("waiting for fire");
                   wait();
                   System.out.println("waiting finished");
               }
           }
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
    }

    public synchronized void fire() {
        this.fire = true;
        // 调用notify是把阻塞在当前WaitThread实例对象上的线程唤醒
        notify();
    }

    public static void main(String[] args) throws InterruptedException {
        WaitThread waitThread = new WaitThread();
        waitThread.start();
        Thread.sleep(1000);
        System.out.println("fire");
        waitThread.fire();
    }
}
